package com.jhf.skypac_pda;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.jhf.skypac_pda.EventMessage.MessageEvent;
import com.jhf.skypac_pda.adapter.MaterialtankfeedingorderListAdapter;
import com.jhf.skypac_pda.base.BaseActivity;
import com.jhf.skypac_pda.db.impl.PermissionDaoImp;
import com.jhf.skypac_pda.model.DialogCallback;
import com.jhf.skypac_pda.model.LzyResponse2;
import com.jhf.skypac_pda.model.MaterialtankfeedingorderModel;
import com.jhf.skypac_pda.utils.ConstantPara;
import com.jhf.skypac_pda.utils.PrefUtils;
import com.jhf.skypac_pda.utils.Urls;
import com.jhf.skypac_pda.view.CustomLoadingMoreFooter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okgo.OkGo;
import okgo.model.HttpHeaders;
import okgo.model.Response;
import okhttp3.RequestBody;

import static com.jhf.skypac_pda.utils.ConstantPara.JSON;

public class FeedingOrderListActivity extends BaseActivity implements XRecyclerView.LoadingListener {
    @BindView(R.id.rv_data)
    XRecyclerView rvData;
    @BindView(R.id.ll_empty)
    LinearLayout imgEmpty;
    @BindView(R.id.et_fragment_search)
    EditText etFragmentSearch;
    @BindView(R.id.ll_delete)
    LinearLayout llDelete;

    private List<MaterialtankfeedingorderModel> mList = new ArrayList<>();
    private MaterialtankfeedingorderListAdapter mAdapter;

    private boolean isFirst = true;
    private int pageNum = 1;
    private String search = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feeding_order_list);

        ButterKnife.bind(this);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvData.setLayoutManager(manager);
        mAdapter = new MaterialtankfeedingorderListAdapter(this, mList);
        rvData.setAdapter(mAdapter);
        final CustomLoadingMoreFooter footer = new CustomLoadingMoreFooter(this);
        rvData.setFootView(footer, new CustomFooterViewCallBack() {
            @Override
            public void onLoadingMore(View yourFooterView) {
                footer.onLoadingMore();
            }

            @Override
            public void onLoadMoreComplete(View yourFooterView) {
                footer.onLoadMoreComplete();
            }

            @Override
            public void onSetNoMore(View yourFooterView, boolean noMore) {
                footer.onSetNoMore();
            }
        });
        rvData.setPullRefreshEnabled(true);
        rvData.setLoadingMoreEnabled(true);
        rvData.setLoadingListener(this);

        // 在你的 XRecyclerView 设置中
        //ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new SimpleItemTouchHelperCallback(rvData, mList));
        //itemTouchHelper.attachToRecyclerView(rvData);

        etFragmentSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    pageNum = 1;
                    getData(etFragmentSearch.getText().toString().trim());
                }
                return false;
            }
        });

        etFragmentSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    llDelete.setVisibility(View.VISIBLE);
                } else {
                    llDelete.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isFirst) {
            isFirst = false;
            pageNum = 1;
            getData("");
        }
    }

    private void getData(String materialTankFeedingOrderCode) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", 1);
        map.put("pageSize", 10);

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);

        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse2<List<MaterialtankfeedingorderModel>>>get(Urls.URL_GET_LIST + "?pageNum=" + pageNum + "&pageSize=" + 10 + "&materialTankFeedingOrderCode=" + materialTankFeedingOrderCode + "&orderByColumn=createTime&isAsc=DESC")
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse2<List<MaterialtankfeedingorderModel>>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse2<List<MaterialtankfeedingorderModel>>> response) {
                        if (null != response.body().rows) {
                            if (pageNum == 1) {
                                mList.clear();
                            }

                            mList.addAll(response.body().rows);

                            if (null == mList || mList.size() == 0) {
                                imgEmpty.setVisibility(View.VISIBLE);
                            } else {
                                imgEmpty.setVisibility(View.GONE);
                            }

                            if (null == response.body().rows || response.body().rows.size() == 0) {
                                rvData.refreshComplete();
                                rvData.loadMoreComplete();
                                rvData.setNoMore(true);

                                return;
                            } else {
                                if (null != response.body().rows && response.body().rows.size() > 0) {
                                    rvData.refreshComplete();
                                    pageNum++;

                                    mAdapter.notifyDataSetChanged();

                                    mAdapter.setViewClickListener(new MaterialtankfeedingorderListAdapter.ViewClickListener() {
                                        @Override
                                        public void post_detail(int pos) {
                                            if (!PermissionDaoImp.getInstance(FeedingOrderListActivity.this).isHavePermission(ConstantPara.PDA_MATERIALTANKFEEDIINGORDER_QUERY)) {
                                                Toast.makeText(FeedingOrderListActivity.this, "您没有此权限", Toast.LENGTH_LONG).show();
                                                return;
                                            }
                                            if (!mList.get(pos).getMaterialTankFeedingOrderStatusDesc().contains("关闭")) {
                                                Intent intent = new Intent(FeedingOrderListActivity.this, NewFeedingDetailActivity.class);
                                                intent.putExtra("orderId", mList.get(pos).getId());
                                                startActivity(intent);
                                            }
                                        }
                                    });
                                }

                                if (response.body().total == mList.size()) {
                                    rvData.refreshComplete();
                                    rvData.loadMoreComplete();
                                    rvData.setNoMore(true);
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse2<List<MaterialtankfeedingorderModel>>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

    }


    @OnClick({R.id.tv_back, R.id.ll_search, R.id.ll_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.ll_search:
                pageNum = 1;
                getData(etFragmentSearch.getText().toString().trim());
                break;
            case R.id.ll_delete:
                etFragmentSearch.setText("");
                break;
        }
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        getData(etFragmentSearch.getText().toString().trim());
    }

    @Override
    public void onLoadMore() {
        getData(etFragmentSearch.getText().toString().trim());
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShutDown(MessageEvent eventMsg) {
        String msg = eventMsg.getMessage();
        if (eventMsg.getType() == 2) {
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).getId().equals(msg)) {
                    mList.get(i).setMaterialTankFeedingOrderStatusDesc("投料完成");
                    mAdapter.notifyDataSetChanged();
                }
            }
        } else if (eventMsg.getType() == 8) {
            // activity关闭，从栈中移除
            //appManager.finishActivity(this);
            if (FeedingOrderListActivity.this.getWindow().getDecorView().getVisibility() == View.VISIBLE) {
                Toast.makeText(this, "登录已过期", Toast.LENGTH_SHORT).show();
                Log.i("登录过期走到这里=========", "FeedingOrderListActivity");
                Intent intent = new Intent(FeedingOrderListActivity.this, LoginActivity.class);
                intent.putExtra("isUpdate", true);
                startActivity(intent);
            }
        }
    }
}
